<template>
  <div class="min-h-screen bg-base-200">
    <!-- 如果已登录，显示用户信息 -->
    <div v-if="user" class="container mx-auto p-4">
      <div class="navbar bg-base-100 rounded-lg shadow-lg mb-4">
        <div class="flex-1">
          <a class="btn btn-ghost text-xl">欢迎，{{ user.nickname }}！</a>
        </div>
        <div class="flex-none gap-2">
          <div class="dropdown dropdown-end">
            <div tabindex="0" role="button" class="btn btn-ghost btn-circle avatar">
              <div class="w-10 rounded-full bg-primary text-primary-content flex items-center justify-center">
                {{ user.nickname.charAt(0).toUpperCase() }}
              </div>
            </div>
            <ul tabindex="0" class="mt-3 z-[1] p-2 shadow menu menu-sm dropdown-content bg-base-100 rounded-box w-52">
              <li>
                <a class="justify-between">
                  个人资料
                  <span class="badge">New</span>
                </a>
              </li>
              <li><a>设置</a></li>
              <li><a @click="handleLogout">退出登录</a></li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 用户信息卡片 -->
      <div class="card bg-base-100 shadow-xl mb-4">
        <div class="card-body">
          <h2 class="card-title">用户信息</h2>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <p class="text-sm text-gray-500">邮箱</p>
              <p class="font-semibold">{{ user.email }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500">昵称</p>
              <p class="font-semibold">{{ user.nickname }}</p>
            </div>
            <div v-if="user.age">
              <p class="text-sm text-gray-500">年龄</p>
              <p class="font-semibold">{{ user.age }}</p>
            </div>
            <div v-if="user.sex">
              <p class="text-sm text-gray-500">性别</p>
              <p class="font-semibold">{{ user.sex }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="card bg-base-100 shadow-xl">
        <div class="card-body">
          <h2 class="card-title">用户列表</h2>
          <div class="overflow-x-auto">
            <table class="table table-zebra">
              <thead>
                <tr>
                  <th>昵称</th>
                  <th>邮箱</th>
                  <th>年龄</th>
                  <th>性别</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="u in users" :key="u.uid">
                  <td>{{ u.nickname }}</td>
                  <td>{{ u.email }}</td>
                  <td>{{ u.age || '-' }}</td>
                  <td>{{ u.sex || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 如果未登录，显示登录/注册表单 -->
    <AuthForm v-else />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { trpc } from './trpc'
import type { User } from '@shared/types'
import AuthForm from './components/AuthForm.vue'

const user = ref<User | null>(null)
const users = ref<User[]>([])

// 从 localStorage 加载用户信息
const loadUser = () => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      user.value = JSON.parse(userStr)
    } catch (e) {
      console.error('解析用户信息失败:', e)
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    }
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const result = await trpc.getUsers.query({ limit: 20, offset: 0 })
    users.value = result.users
  } catch (error: any) {
    console.error('加载用户列表失败:', error)
  }
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  user.value = null
  users.value = []
}

onMounted(() => {
  loadUser()
  if (user.value) {
    loadUsers()
  }

  // 监听 storage 变化（当登录/注册成功时）
  window.addEventListener('storage', () => {
    loadUser()
    if (user.value) {
      loadUsers()
    }
  })

  // 也监听当前页面的 localStorage 变化（用于同一窗口内的变化）
  setInterval(() => {
    const userStr = localStorage.getItem('user')
    if (userStr && !user.value) {
      loadUser()
      if (user.value) {
        loadUsers()
      }
    } else if (!userStr && user.value) {
      user.value = null
      users.value = []
    }
  }, 500)
})
</script>

<style scoped>
/* 额外的样式可以在这里添加 */
</style>
